package com.gxuwz.util;

import com.gxuwz.entity.vo.PageVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
public class PageUtil {

    public PageVo queryForPage(String sql, Integer pageNum, Integer pageSize, Object[] params, RowMapper rowMapper,JdbcTemplate jdbcTemplate) throws DataAccessException {
        PageVo pageVo = new PageVo();
        //获取总记录数
        String countSql = "select count(1) as count from (" + sql + ") temp";
        List totals;
        if(params == null){
            totals = jdbcTemplate.queryForList(countSql, Integer.class);
        } else {
            totals = jdbcTemplate.queryForList(countSql, params, Integer.class);
        }
        pageVo.setTotal((Integer) totals.get(0));
        pageVo.setPageNum(pageNum);
        pageVo.setPageSize(pageSize);
        //获取页数
        int pageCount = pageVo.getTotal() % pageVo.getPageSize();
        pageVo.setPages(pageCount == 0 ? (pageVo.getTotal() / pageVo.getPageSize()) : (pageVo.getTotal() / pageVo.getPageSize() + 1));
        sql += parseLimit(pageVo);
        log.info("sql:"+sql);
        List data = jdbcTemplate.query(sql, params, rowMapper);
        pageVo.setList(data);
        return pageVo;
    }

    private String parseLimit(PageVo pageVo){
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(" limit ");
        stringBuffer.append(pageVo.getPageSize());
        stringBuffer.append(" offset ");
        stringBuffer.append(pageVo.getPageSize()*(pageVo.getPageNum() - 1));
        return stringBuffer.toString();
    }
}
